import json
import socket

import time  # TODO: fix json reads on the socket and remove

HOST = 'localhost'
PORT = 6546


class Bot:
	def __init__(self, name='BOT', host='localhost', port=PORT, initiate_start=False):
		self.name = name
		self.ssock = None
		self.initiate_start = initiate_start

	def set_name(self, name):
		self.name = name

	@classmethod
	def build_action(cls, action, rest={}):
		ret = {'action': action}
		ret = ret | rest
		return ret

	@classmethod
	def choose_row(cls, row_index):
		return cls.build_action('select_row', {'i': row_index})

	@classmethod
	def give_card(cls, card):
		return cls.build_action('give_card', {'card': card})

	@classmethod
	def start_game(cls):
		time.sleep(1)
		return cls.build_action('start')

	def bot_give_card(self, msg):
		pass

	def bot_select_row(self, msg):
		pass

	def send_msg(self, msg):
		jmsg = json.dumps(msg)
		print('msg to send:', jmsg)
		self.ssock.send(bytes(jmsg, 'utf-8'))

	def send_name(self):
		name_action = self.build_action('set_name', {'name': self.name})
		self.send_msg(name_action)

	def connect(self, host='localhost', port=6546):
		self.ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.ssock.connect((host, port))
		self.send_name()
		if self.initiate_start:
			self.send_msg(self.start_game())

	def play(self):
		def get_msg_type(msg):
			try:
				typ = msg.get('type')
			except:
				print('unable to get type')
				exit(8)
			return typ

		def get_action(msg):
			try:
				action = msg.get('action')
			except:
				print('unable to get action')
				exit(9)
			return action

		while True:
			bmsg = self.ssock.recv(1024)
			if len(bmsg) <= 0:
				print('read 0; hangup')
				exit(3)
			jmsg = str(bmsg, 'utf-8').strip()
			msg = json.loads(jmsg)
			print('msg:', msg)
			msg_type = get_msg_type(msg)
			# print('parsed msg_type:', msg_type)
			if msg_type == 'query':
				action = get_action(msg)
				print('parsed action:', action)
				if action == 'give_card':
					self.bot_give_card(msg)
				elif action == 'select_row':
					self.bot_select_row(msg)
				else:
					print('unknown message action:', action)
			elif msg_type == 'info':
				print('info type is not implemented')
			else:
				print('unknown message type:', msg_type)


